import {layout,scal,fontSize} from './config';
import Anime from './Anime';

var tmp_panel = '<div class="panel"></div>';
var p_renderNow = (layout.panelHeight - layout.panelPaddingY)/layout.panelHeight;
var p_renderNext = (layout.NumberMargin - layout.panelPaddingY)/layout.panelHeight;
var char_offset = {
    1:1.5
}

function Panel(left,Rollpad,charStr){
    
    var inAnime = true; //这两个值初始值为true是为了渲染第一帧
    var hasAnime = true;
    var charSet = (charStr||'0123456789').split('');
    var max = charSet.length;
    var count = 0; //关键要素count,决定动画进度
    var animeQueue = []; //动画队列

    this.pad = Rollpad;
    this.left = left;

    var el = document.createElement('div');
    el.className = 'panel';
    el.style.left = left + 'px';
    el.style.width = layout.panelWidth + 'px';
    el.style.height = layout.panelHeight + 'px';

    Rollpad.$el.children[1].appendChild(el);

    //收到时间戳通知，计算绘制函数并返回
    this.stab = function(timeStamp){
        if(!hasAnime)return;
        var currentAnime = animeQueue[0];
        var p = currentAnime&&currentAnime.percent||0;
        if(currentAnime&&p>0){
            inAnime = true;
            count = currentAnime.value;
        }

        if(inAnime){
            if(p>=1){
                animeQueue.shift();
                inAnime = false;
            }
            hasAnime = animeQueue.length!=0;
            return function(Q){
                clear(Q);
                draw(Q);
            }
            
        }
    }

    //接收anime对象，压入动画队列
    this.reciveAnime = function(animes){
        animes = animes instanceof Anime?[animes]:animes;
        if(animes instanceof Array){
            animes.forEach(v=>{
                if(v instanceof Anime){
                    animeQueue.push(v);
                    hasAnime = true;
                }
            })
        }
        
    }

    this.destory = ()=>{
        Rollpad.$el.children[1].removeChild(el);
    }

    //工具方法
    //根据count绘制字符
    var draw = function (Q){
        var p = count%1;
        var nnow = Math.floor(count%max);
        var nnext = (nnow+1)%max;
        if(p<p_renderNow){
            Q.fillText(charSet[nnow],getX(nnow),getY(layout.panelHeight*p))
        }
        if(p>p_renderNext){
            Q.fillText(charSet[nnext],getX(nnext),getY(-layout.panelHeight*(1-p)))
        }
    }.bind(this);

    //清空当前区域画布
    var clear = function (Q){
        Q.clearRect(left*scal,0,layout.panelWidth*scal,layout.panelHeight*scal);
    }.bind(this);

    //计算X坐标 根据字符修正偏差
    var getX = function (char){
        var x = char_offset[char]||0;
        return (x + left + layout.panelPaddingX)*scal;
    }.bind(this);

    //计算Y坐标
    var getY = function (y){
        y = y||0;
        return (y + layout.panelPaddingY + fontSize)*scal;
    };

}

export default Panel;